import { Button } from 'antd'
import { useState } from 'react'

import { getAppState } from '@/utils/dvaUtil/index'

/**
 * @typedef {Object} OtherProps
 * @property {() => Promise} [onSubmit] 提交
 * @property {string} [permissionKey] 权限值
 */

/**
 * @typedef {import("antd/es/button").ButtonProps & OtherProps} AekButtonProps
 */

/**
 * @param {AekButtonProps} props
 * @returns
 */
const AekButton = props => {
  const [loading, setLoading] = useState(false)
  const { permissionKey, onClick: propOnClick, onSubmit, ...other } = props

  const { loginInfo } = getAppState()

  const onClick = async e => {
    propOnClick?.(e)
    if (!onSubmit) return
    setLoading(true)
    await onSubmit().finally(() => {
      setLoading(false)
    })
  }

  return loginInfo.authorization.authorities.includes(permissionKey) || !permissionKey ? (
    <Button {...other} loading={loading} onClick={onClick} />
  ) : undefined
}

export default AekButton
